﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using easyVal.ServerSide;
using easyVal.Web;
using easyVal.Web.Demo.BL;
using easyVal.Web.Demo.Entities;
using easyVal.Web.Demo.Util;
using easyVal.Web.Extensions;

namespace easyval.web.demo
{
    public partial class WithEasyValPage : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Clear validation
            txtFirstName.ClearValidation();
            txtEmail.ClearValidation();
            txtDesiredSalary.ClearValidation();

            // Clear Form
            lblSubmitted.Text = "";
            lblServerErrors.Text = "";

            // Initialize
            InitializeClientValidation();
        }

        private void InitializeClientValidation()
        {
            // Initialize Validation For Employee
            ClientModelValidation valE = new ClientModelValidation(typeof (Employee));
            valE.AddValidation(txtFirstName, "FirstName");
            valE.AddValidation(txtEmail, "Email");
            valE.AddValidation(txtDesiredSalary, "DesiredSalary");
            valE.AddValidation(txtPhone, "PhoneNumber");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                panelFeedback.Visible = true;

                var employee = new Employee();
                employee.FirstName = txtFirstName.Text;
                employee.Email = txtEmail.Text;
                employee.DesiredSalary = TryParseUtil.TryParseIntOrNeg1(txtDesiredSalary.Text);
                employee.PhoneNumber = txtPhone.Text;

                // Save
                EmployeeBL.SaveEmployeeEasy(employee);

                lblSubmitted.Text = "submitted " + DateTime.Now.ToString("hh:mm:ss");
            }
            catch (Exception ex)
            {
                DisplayError(lblServerErrors, ex);
            }
        }

        private static void DisplayError(Label lbl, Exception ex)
        {
            if (ex is RulesException)
            {
                var rex = (RulesException) ex;
                lbl.Text += "<span style='color:gray'>Server Side Error" + ((rex.Errors.Count > 1) ? "s" : "") +
                            "</span>";
                foreach (ErrorInfo ei in rex.Errors)
                {
                    lbl.Text += "<br/> " + ei.ErrorMessage;
                }
            }
            else
            {
                lbl.Text = ex.ToString();
            }
        }
    }
}